<template>
  <van-nav-bar
    title="登录"
    left-text="返回"
    left-arrow
    @click-left="onClickLeft"
  />

  <van-form @submit="onSubmit">
    <van-cell-group inset>
      <van-field
        v-model="username"
        name="用户名"
        label="用户名"
        placeholder="用户名"
        :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <van-field
        v-model="password"
        type="password"
        name="密码"
        label="密码"
        placeholder="密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
    </van-cell-group>
    <div style="margin: 16px">
      <van-button round block type="primary" native-type="submit">
        登录
      </van-button>
    </div>
    <div class="login-register" @click="onGoRegister">手机快速注册</div>
  </van-form>
</template>

<script>
import { loginApi } from "@/api/my.js";
import { showToast } from "vant";
export default {
  name: "Login",
  data() {
    return {
      username: "",
      password: "",
    };
  },
  methods: {
    // 返回上一级
    onClickLeft() {
      this.$router.back(-1);
    },
    // 表单提交，登陆判断
    async onSubmit() {
      let res = await loginApi({
        loginname: this.username,
        password: this.password,
      });
      if (res.data.code === "200") {
        showToast("登陆成功");
        sessionStorage.setItem("token", res.data.data.token);
        sessionStorage.setItem("userid", res.data.data.userid);
        if (this.$route.query.path) {
          this.$router.replace(this.$route.query.path);
        } else {
          this.$router.replace("/Home");
        }
      } else {
        showToast("你好,你的手机号或密码错误!");
      }
    },
    // 快速注册
    onGoRegister() {
      this.$router.push("/Register");
    },
  },
};
</script>

<style scoped>
.login-register {
  float: right;
  padding: 0.2rem;
  color: rgb(72, 123, 218);
}
</style>
